<script setup>
import { ref, onMounted, onUnmounted, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import { Menu } from '@element-plus/icons-vue'
import { endorsementsNavigation } from '@/api/endorsements' // 请根据你的实际文件路径导入

const activeIndex = ref('')
const isTop = ref(true)
const isMobileMenuOpen = ref(false)
const router = useRouter()

// endorsements 改为从接口获取
const endorsements = ref([])
const loading = ref(false)
const error = ref(null)

// 获取代言导航数据
const fetchEndorsementsNavigation = async () => {
  loading.value = true
  error.value = null
  try {
    const response = await endorsementsNavigation()
    endorsements.value = response.data.data
  } catch (err) {
    console.error('获取代言导航数据失败:', err)
    error.value = err.message || '获取数据失败，请稍后重试'
  } finally {
    loading.value = false
  }
}

const isMobile = computed(() => window.innerWidth <= 768)

const handleScroll = () => {
  isTop.value = window.scrollY < 10
}

const toggleMobileMenu = () => {
  isMobileMenuOpen.value = !isMobileMenuOpen.value
}

const closeMobileMenu = () => {
  isMobileMenuOpen.value = false
}

const handleSelect = (key) => {
  closeMobileMenu()
  if (key === '1') {
    router.push('/')
  } else if (key.startsWith('endorse-')) {
    const id = key.split('-')[1]
    router.push(`/endorsement/${id}`)
  } else if (key === '3') {
    router.push('/opus')
  } else if (key === '4') {
    router.push('/production')
  } else if (key === '5') {
    router.push('/artists')
  } else if (key === '6') {
    router.push('/news')
  } else if (key === '7') {
    router.push('/about')
  } else if (key === '8') {
    router.push('/products')
  }
}

// 根据当前路由设置 activeIndex
const updateActiveIndex = (path) => {
  if (path === '/') {
    activeIndex.value = '1'
  } else if (path.startsWith('/endorsement/')) {
    const id = path.split('/endorsement/')[1]
    activeIndex.value = `endorse-${id}`
  } else if (path === '/opus') {
    activeIndex.value = '3'
  } else if (path === '/production') {
    activeIndex.value = '4'
  } else if (path === '/artists') {
    activeIndex.value = '5'
  } else if (path === '/news') {
    activeIndex.value = '6'
  } else if (path === '/about') {
    activeIndex.value = '7'
  } else if (path === '/products') {
    activeIndex.value = '8'
  } else {
    activeIndex.value = ''
  }
}

onMounted(() => {
  fetchEndorsementsNavigation()
  updateActiveIndex(router.currentRoute.value.path)

  window.addEventListener('scroll', handleScroll)
  window.addEventListener('resize', () => {
    if (!isMobile.value) closeMobileMenu()
  })
})

// 监听路由变化，实时更新高亮
watch(
    () => router.currentRoute.value.path,
    (newPath) => {
      updateActiveIndex(newPath)
    },
    { immediate: true }
)

onUnmounted(() => {
  window.removeEventListener('scroll', handleScroll)
})
</script>

<template>
  <header class="tencent-header" :class="{ 'scrolled': !isTop }">
    <div class="header-container">
      <div class="header-left">
        <div class="logo">
          <router-link to="/">
            <img src="../assets/images/logo.png" alt="Tencent" />
          </router-link>
        </div>
        <div class="mobile-menu-button" @click="toggleMobileMenu">
          <el-icon><Menu /></el-icon>
        </div>
      </div>

      <!-- 桌面端菜单 -->
      <el-menu
          v-model="activeIndex"
          class="el-menu-demo desktop-menu"
          mode="horizontal"
          @select="handleSelect"
          :background-color="isTop ? 'transparent' : '#fff'"
          :text-color="isTop ? 'pink' : '#333'"
          :active-text-color="isTop ? '#ffd04b' : '#409EFF'"
      >
        <el-menu-item index="1">首页</el-menu-item>
        <el-sub-menu index="2">
          <template #title>代言</template>
          <el-menu-item
              v-for="item in endorsements"
              :key="item.id"
              :index="`endorse-${item.id}`"
          >
            {{ item.name }}
          </el-menu-item>
        </el-sub-menu>
        <el-menu-item index="3">作品集</el-menu-item>
        <el-menu-item index="4">制作服务</el-menu-item>
        <el-menu-item index="5">艺术家</el-menu-item>
        <el-menu-item index="6">新闻</el-menu-item>
        <el-menu-item index="7">关于我们</el-menu-item>
        <el-menu-item index="8">产品</el-menu-item>
      </el-menu>

      <!-- 移动端菜单 -->
      <div class="mobile-menu-overlay" v-if="isMobileMenuOpen" @click="closeMobileMenu"></div>
      <div class="mobile-menu" :class="{ 'open': isMobileMenuOpen }">
        <el-menu
            v-model="activeIndex"
            @select="handleSelect"
            :background-color="isTop ? 'transparent' : '#fff'"
            :text-color="isTop ? 'pink' : '#333'"
            :active-text-color="isTop ? '#ffd04b' : '#409EFF'"
        >
          <el-menu-item index="1">首页</el-menu-item>
          <el-sub-menu index="2">
            <template #title>代言</template>
            <el-menu-item
                v-for="item in endorsements"
                :key="item.id"
                :index="`endorse-${item.id}`"
            >
              {{ item.name }}
            </el-menu-item>
          </el-sub-menu>
          <el-menu-item index="3">作品集</el-menu-item>
          <el-menu-item index="4">制作服务</el-menu-item>
          <el-menu-item index="5">艺术家</el-menu-item>
          <el-menu-item index="6">新闻</el-menu-item>
          <el-menu-item index="7">关于我们</el-menu-item>
          <el-menu-item index="8">产品</el-menu-item>
        </el-menu>
      </div>
    </div>
  </header>
</template>


<style scoped>
.tencent-header {
  position: fixed;
  width: 100%;
  top: 0;
  z-index: 1000;
  transition: all 0.3s ease;
}

.tencent-header:not(.scrolled) {
  background-color: transparent;
  box-shadow: none;
}

.tencent-header.scrolled {
  background-color: #fff;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.header-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  position: relative;
}

/* 新增header-left容器样式 - 使用Flexbox实现左右布局 */
.header-left {
  display: flex;
  align-items: center;
  justify-content: space-between; /* 确保Logo和菜单按钮分居两侧 */
  width: 100%; /* 占据整个宽度 */
}

.logo img {
  height: 40px;
  transition: all 0.3s ease;
}

.tencent-header:not(.scrolled) .logo img {
  filter: brightness(0) invert(1);
}

.tencent-header.scrolled .logo img {
  filter: none;
}

.el-menu-demo {
  flex: 1;
  border-bottom: none;
}

:deep(.el-menu) {
  background-color: transparent !important;
}

:deep(.el-menu--horizontal.el-menu) {
  border-bottom: none !important;
}

:deep(.el-menu--horizontal > .el-menu-item),
:deep(.el-menu--horizontal > .el-sub-menu .el-sub-menu__title) {
  height: 60px;
  line-height: 60px;
  transition: color 0.3s ease;
  background-color: transparent !important;
}

/* 取消所有状态下的背景色 */
:deep(.el-menu--horizontal > .el-menu-item:hover),
:deep(.el-menu--horizontal > .el-sub-menu:hover .el-sub-menu__title),
:deep(.el-menu--horizontal > .el-menu-item:focus),
:deep(.el-menu--horizontal > .el-menu-item:active),
:deep(.el-menu--horizontal > .el-menu-item.is-active),
:deep(.el-menu--horizontal > .el-sub-menu.is-active .el-sub-menu__title) {
  background-color: transparent !important;
}

.tencent-header:not(.scrolled) :deep(.el-menu--horizontal > .el-menu-item),
.tencent-header:not(.scrolled) :deep(.el-menu--horizontal > .el-sub-menu .el-sub-menu__title) {
  color: white !important;
}

.tencent-header.scrolled :deep(.el-menu--horizontal > .el-menu-item),
.tencent-header.scrolled :deep(.el-menu--horizontal > .el-sub-menu .el-sub-menu__title) {
  color: #333 !important;
}

.tencent-header.scrolled :deep(.el-menu--horizontal > .el-menu-item.is-active),
.tencent-header.scrolled :deep(.el-menu--horizontal > .el-sub-menu.is-active .el-sub-menu__title) {
  color: #409EFF !important;
  border-bottom-color: #409EFF !important;
}

/* 移动端菜单按钮 */
.mobile-menu-button {
  display: none;
  font-size: 24px;
  cursor: pointer;
  color: white;
  z-index: 1001;
}

.tencent-header.scrolled .mobile-menu-button {
  color: #333;
}

/* 移动端菜单 */
.mobile-menu {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 50vh;
  background-color: white;
  transform: translateY(-100%);
  transition: transform 0.3s ease;
  z-index: 1002;
  overflow-y: auto;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.mobile-menu.open {
  transform: translateY(0);
}

.mobile-menu-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 1001;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header-container {
    padding: 10px 20px;
    flex-wrap: nowrap; /* 禁止换行 */
  }

  /* 移动端：确保Logo和菜单按钮左右分布 */
  .header-left {
    display: flex;
    justify-content: space-between; /* Logo在左，菜单按钮在右 */
    align-items: center; /* 垂直居中 */
  }

  .desktop-menu {
    display: none;
  }

  .mobile-menu-button {
    display: block;
    font-size: 30px; /* 增大菜单图标 */
  }

  .logo img {
    height: 40px; /* 缩小移动端Logo尺寸 */
  }

  :deep(.el-menu) {
    width: 100%;
  }

  :deep(.el-menu-item),
  :deep(.el-sub-menu .el-sub-menu__title) {
    height: 50px;
    line-height: 50px;
  }
}

@media (min-width: 769px) {
  .mobile-menu-button,
  .mobile-menu,
  .mobile-menu-overlay {
    display: none;
  }

  /* 修复：桌面端显示header-left容器 */
  .header-left {
    display: flex;
    width: auto;
    justify-content: flex-start; /* Logo居左 */
  }

  /* 确保桌面端菜单显示 */
  .desktop-menu {
    display: flex;
  }
}
</style>
